<?php

namespace Authentication\Service;

use Zend\Authentication\Adapter\AbstractAdapter;
use Zend\Authentication\Result;
use User\Repository\UserRepository;

class UserRepositoryAdapter extends AbstractAdapter {

    /**
     * @var UserRepository
     */
    private $userRepository;
    
    public function authenticate() {
        if (!$this->identity) {
             throw new Exception\RuntimeException('A value for the identity was not provided prior to authentication with DbTable.');
        } elseif (!$this->credential) {
             throw new Exception\RuntimeException('A credential value was not provided prior to authentication with DbTable.');
        }
        
        $user = $this->userRepository->findUserByLogin($this->identity);
        if(!$user) {
            return new Result(Result::FAILURE_IDENTITY_NOT_FOUND, null, array('User not found.'));
        }
        
        if(!$user->getPassword()) {
            return new Result(Result::FAILURE, null, array('User account inactive.'));
        }
        
        if($user->getPassword() !== $this->credential) {
            return new Result(Result::FAILURE_CREDENTIAL_INVALID, null, array('Invalid password.'));
        }
        
        return new Result(Result::SUCCESS, $user, array('Authentication successful.'));
    }
    
    public function setUserRepository(UserRepository $userRepository) {
        $this->userRepository = $userRepository;
    }

}